<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta http-equiv="cache-control" content="no-cache" />
		<title>告警事件</title>
		<link rel="stylesheet" href="../../assets/less/base/main.css" />
		<link rel="stylesheet" href="../../assets/less/message/index.css" />
	</head>

	<body>
		<div id="app">
			<div class="iot-device-message" :style="{'height': height,'padding':pageType==='message'?'0':'24px 12px 24px 24px'}" v-show="isShow">
				<div class="iot-device-message-header" v-show="pageType!=='message'">
                    <div class="page-title">{{pageName}}</div>
                    <div class="page-title-extra" @click="handleMore()">更多</div>
                </div>
				<div class="page-list">
					<template v-if="messageList&&messageList.length > 0">
						<div class="message-box" v-for="(item,index) in messageList" :key="index">
							<div class="message-header">
								<div class="message-title-badge message-title-badge-red"></div>
								<span class="message-title">{{getMessageTitle(item.title)}}</span>
								<img src="../../assets/images/more.png" class="message-title-extra"
									@click="handleAction(item)"></img>
							</div>
							<div class="message-content" :style="{ width: item.imageContent&&item.imageContent.length > 50 ? '74%' : '100%' }">
								{{ item.textContent&&item.textContent.length>30?item.textContent.substring(0,50)+'...':item.textContent }}
							</div>
							<img :src="item.imageContent" class="iot-el-img message-content-img"
								v-if="item.imageContent&&item.imageContent.length > 50"></img>
							<div class="message-footer">
								<div class="footer-time">{{ util.formatDate(item.createDateTime) }}</div>
								<div class="footer-deal" style="cursor: pointer;" @click="handleDeal(item)">{{ item.confirmor ? '处理' : '处理' }}</div>
							</div>
						</div>
					</template>
					<div :class="pageType==='message'?'no-message-small':'no-message'"
						v-else-if="util.isEmpty(messageList)&&pageType!=='message'">
						<img src="../../assets/svg/icon-no-message.svg" alt="">
						<p>目前没有事件</p>
					</div>
				</div>
			</div>
		</div>
		<script src="../../config.js"></script>
		<script src="../../assets/js/main.js" type="module"></script>
		<script src="../../assets/lib/signalr.min.js"></script>
		<script type="module">
			// 右侧图表页面ID
			const _RIGHT_CHART_PAGE_NAME_ = '大屏右侧数据面板'
			// 创建Vue实例
			new Vue({
				el: '#app', // 绑定元素
				data: {
					pageNo: 1,
					pageSize: 20,
					pageName: '告警事件',
					messageList: [],
					pageType: 'message',
					height: '500px',
					isShow: false,
					connection: null,
				},
				mounted() {
					this.isShow = true
					var result = util.queryUrlParams(location.href)
					let pageType = util.isNotEmpty(result) ? result['pageType'] : 'message'
					this.pageType = pageType || 'message'
					this.pageName = this.getPageName(this.pageType)
					let height = util.isNotEmpty(result) ? result['height'] : '500'
					this.height = (height || '500') + 'px'
					if (this.pageType === 'car') {
						let params = {
							messageType: 5,
							messageContentType: 3,
							deviceTypeLists: ['车行道闸'],
						}
						this.loadMessageList(params)
					}else if(this.pageType==='message'){
						let params = {
							messageLevel: '2,3,4',
							deviceTypeLists: ['空调','漏水','电池组','温湿度','电量仪','烟感','UPS','声光报警器','数据采集器'],
						}
						this.loadMessageList(params)
					}else  {
						let params = {
							messageLevel: '2,3,4',
							deviceTypeLists: ['摄像头'],
						}
						this.loadMessageList(params)
					}
					this.initSignalRConnection()
				},
				methods: {
					handleDeal(item){
						let iotUrl=window.iotWebConfig?.iotUrl
						let redirectUrl = iotUrl +"/#/message/alarmInfo?id="+item.id+'&fullscreen=true&theme=dark&closable=false'
						let realUrl = iotUrl +
                            "/#/oauth?username=admin&password=4b78e581bdaffa037a6b11d58bdc934a&redirectUrl="+encodeURIComponent(redirectUrl)
                        this.CreateTemperaturePlane("SharedMessageWindow",
							-510,
							-200,
							1020,
							574,
							realUrl,
							5)
					},
                    handleMore(){
                        let redirectUrl = window.iotWebConfig?.iotUrl +"/#/message/device"
                            Fuck(
                            "func_html_page",
                            null,
                            "open_url",
                            window.iotWebConfig?.iotUrl +
                            "/#/oauth?username=admin&password=4b78e581bdaffa037a6b11d58bdc934a&redirectUrl="+encodeURIComponent(redirectUrl)
                        );
                    },
					handleAction(row) {
						// 调用定位接口
						let deviceId = row.device ? row.device.id : ''
						if (deviceId) {
							Fuck("func_search", null, "focus", deviceId);
						}
					},
					// 获取设备事件
					loadMessageList(paramsObj) {
						let params = {
							pageNo: this.pageNo,
							pageSize: this.pageSize,
							beginTime: util.getDay(-30),
							t: new Date().getTime(),
							...paramsObj
						}
						webApi.getDeviceMessages2(params).then(res => {
							if (res.code === 0) {
								let list = util.getArrData(res.result.data)
								if (util.isNotEmpty(list)) {
									list.forEach(x => {
										x=this.getMessageObj(x)
									})
								}
								console.log(list);
								this.messageList = list
							}
						})
					},
					initSignalRConnection() {
						// 连接到 SignalR 服务  
						this.connection = new signalR.HubConnectionBuilder()
							.withUrl(window.iotWebConfig?.iotUrl + "/signalr/messagehub") // 替换为你的 SignalR Hub 路由  
							.configureLogging(signalR.LogLevel.Information) // 可选：配置日志记录级别  
							.build();
						// 开始连接  
						this.connection.start().then(res => {
							console.log('message signalr连接成功');
						}).catch(err => {
							console.log(err.toString())
						});

						this.connection.on('AddNewMessageEvent2', res => {
							if(res.level<2){
								return
							}
							if (this.pageType === 'car' && res.device && res.device.product && res.device.product
								.deviceType === '车行道闸') {
								this.messageList.unshift(this.getMessageObj(res))
							} else if (this.pageType === 'monitor' && res.device && res.device.product && res
								.device.deviceType === '摄像头') {
								this.messageList.unshift(this.getMessageObj(res))
							} else if (this.pageType === 'message' && res.level === 2) {
								this.messageList.unshift(this.getMessageObj(res))
							}
							if (this.messageList.length > 20) {
								this.messageList.pop()
							}
						})

						// 当连接关闭时（如刷新页面）  
						this.connection.onclose(async () => {
							console.log("Connection closed. Retrying...");
							// 尝试重新连接  
							await this.startConnection();
						});
					},
					async startConnection() {
						try {
							await this.connection.start();
							console.log("SignalR Connected.");
						} catch (err) {
							console.log(err);
							setTimeout(() => this.startConnection(), 5000); // 每5秒重试一次  
						}
					},
					getMessageObj(res) {
						let content = res.content;
						if (content && Array.isArray(content)) {
							let imageContent = content.find(
								(con) => con.contentType === 2 || con.contentType === 3
							);
							let imageContentStr = imageContent ? imageContent.content : "";
							res.imageContent = imageContentStr ?
								imageContentStr.startsWith("http") ?
								imageContentStr :
								window.iotWebConfig?.iotUrl + "/" + imageContentStr :
								"";
							res.textContent = content
								.filter((con) => con.contentType < 2)
								.map((c) => c.content)
								.join(";");
						}
						return res
					},
					getMessageTitle(title) {
						let str = title
						if (title && title.indexOf('|') != -1) {
							let arr = title.split('|')
							if (arr.length >= 3) {
								str = arr[0] + '-' + arr[1] + ' 触发了 ' + arr[2] + ' 事件'
							} else if (arr.length == 2) {
								str = arr[0] + '触发了 ' + arr[1] + ' 事件'
							}
						}
						return str
					},
					getPageName(type) {
						let result = ''
						switch (type) {
							case 'car':
								result = '车辆进出记录'
								break
							case 'air':
							case 'access':
							case 'light':
							case 'message':
								result = ''
								break
							case 'fire':
							case 'monitor':
								result = '事件列表'
								break
							case 'face':
								result = '人脸识别'
								break
						}
						return result
					},
					CreateTemperaturePlane(id, x, y, width, height, source, anchor = 1, blur = false, close_button = true) {
						var arg = {
						id,
						x,
						y,
						width,
						height,
						anchor,
						source,
						transform: "0,0",
						blur,
						close_button,
						radius: 0,
						group: "_RDP_",
						/*bind3d: {
							type: "value",
							target: "0,0,0",
							offset: "0,0,0"
						},*/
						animation: {
							name: "fade+transform",
							from_x: 24,
						},
						};

						Fuck("func_html_chrome", null, "create_page", JSON.stringify(arg));
					}
				}
			})
		</script>
	</body>

</html>